<?php
/**
 * Created by PhpStorm.
 * User: tony
 * Date: 2018/6/4
 * Time: 11:20
 */

namespace app\modules\v1\controllers;

use app\config\Status;
use app\models\Branch;
use app\models\FlowType;
use app\models\Project;
use app\models\ProjectFh;
use app\models\ProjectYt;
use app\models\User;
use app\modules\v1\controllers\parent\ParentController;
use yii\data\ActiveDataProvider;

class ProjectController extends ParentController
{
    public function actionIndex(){
        return 21321;
        $params = \Yii::$app->request->getQueryParams();
        $query = Project::find()->with(['leadingUser', 'customer', 'flowType'])->joinWith(['projectFh', 'projectYt']);


        if (isset($params['scale'])) {
            $query->andWhere(['hj_project_fh.scale'=> $params['scale']]);
        }

        if (isset($params['type'])) {
            $query->andWhere(['hj_project_fh.type'=> $params['type']]);
        }

        if (isset($params['yt_type'])) {
            $query->andWhere(['hj_project_yt.yt_type'=> $params['yt_type']]);
        }

        if (isset($params['start_at'])) {
            $query->andWhere(['>=', 'created_at', round($params['start_at'] / 1000)]);
        }

        if (isset($params['end_at'])) {
            $query->andWhere(['<=', 'created_at', round($params['end_at'] / 1000)]);
        }

        if (isset($params['name'])) {
            $query->andWhere(['like', 'name', $params['name']]);
        }

        if (isset($params['planner'])) {
            $query->andWhere(['like', 'planner', $params['planner']]);
        }
        if (isset($params['project_no']) && $params['project_no']) {
            $query->andWhere(['like', 'project_no', $params['project_no']]);
        }


        if (isset($params['branch_id'])) {
            $query->andWhere(['branch_id'=> $params['branch_id']]);
        }

        if (isset($params['receive_status'])) {
            $query->andWhere(['receive_status'=> $params['receive_status']]);
        }

        if (isset($params['customer_id'])) {
            $query->andWhere(['customer_id'=> $params['customer_id']]);
        }

        if (isset($params['origin_type'])) {
            $query->andWhere(['origin_type'=> $params['origin_type']]);
        }

        if (isset($params['flow_status'])) {
            $query->andWhere(['flow_status'=> $params['flow_status']]);
        }

        if (isset($params['sign_status'])) {
            $query->andWhere(['sign_status'=> $params['sign_status']]);
        }

        if (isset($params['progress_status'])) {
            $query->andWhere(['progress_status'=> $params['progress_status']]);
        }

        if (isset($params['project_type_id'])) {
            $query->andWhere(['project_type_id'=> $params['project_type_id']]);
        }

        if(isset($params['valid'])){
            $query->andWhere(['hj_project.valid' => (int)$params['valid']]);
        } else {
            $query->andWhere(['hj_project.valid'=>1]);
        }

        $pageSize = 10;
        if(isset($params['pageSize'])){
            $pageSize = (int)$params['pageSize'];
        }
        return new ActiveDataProvider([
            // 使用with方法实现贪加载
            'query' => $query,
            // 分页信息
            'pagination' => [
                'pageSize' => $pageSize,
            ],
            // 排序信息
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
        ]);
    }

    // 回收站功能
    public function actionRecover(){
        $params = \Yii::$app->request->getQueryParams();
        $query = Project::find()->with(['leadingUser', 'customer', 'flowType' => function($res) {
            $res->andWhere(['valid' => 1])->orderBy('flow_id ASC');
        }])->joinWith('projectFh');

        if (isset($params['scale'])) {
            $query->andWhere(['hj_project_fh.scale'=> $params['scale']]);
        }

        if (isset($params['type'])) {
            $query->andWhere(['hj_project_fh.type'=> $params['type']]);
        }

        if (isset($params['start_at'])) {
            $query->andWhere(['>=', 'created_at', round($params['start_at'] / 1000)]);
        }

        if (isset($params['end_at'])) {
            $query->andWhere(['<=', 'created_at', round($params['end_at'] / 1000)]);
        }

        if (isset($params['name'])) {
            $query->andWhere(['like', 'name', $params['name']]);
        }

        if (isset($params['planner'])) {
            $query->andWhere(['like', 'planner', $params['planner']]);
        }
        if (isset($params['project_no']) && $params['project_no']) {
            $query->andWhere(['like', 'project_no', $params['project_no']]);
        }


        if (isset($params['branch_id'])) {
            $query->andWhere(['branch_id'=> $params['branch_id']]);
        }

        if (isset($params['receive_status'])) {
            $query->andWhere(['receive_status'=> $params['receive_status']]);
        }

        if (isset($params['customer_id'])) {
            $query->andWhere(['customer_id'=> $params['customer_id']]);
        }

        if (isset($params['origin_type'])) {
            $query->andWhere(['origin_type'=> $params['origin_type']]);
        }

        if (isset($params['flow_status'])) {
            $query->andWhere(['flow_status'=> $params['flow_status']]);
        }

        if (isset($params['sign_status'])) {
            $query->andWhere(['sign_status'=> $params['sign_status']]);
        }

        if (isset($params['progress_status'])) {
            $query->andWhere(['progress_status'=> $params['progress_status']]);
        }

        if (isset($params['project_type_id'])) {
            $query->andWhere(['project_type_id'=> $params['project_type_id']]);
        }

        $query->andWhere(['valid'=>0]);
        $pageSize = 10;
        if(isset($params['pageSize'])){
            $pageSize = (int)$params['pageSize'];
        }
        return new ActiveDataProvider([
            // 使用with方法实现贪加载
            'query' => $query,
            // 分页信息
            'pagination' => [
                'pageSize' => $pageSize,
            ],
            // 排序信息
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
        ]);
    }

    public function actionTask() {
        $params = \Yii::$app->request->getQueryParams();
        $id   = \Yii::$app->user->id; // 根据token获取到的id
        $user = User::findOne($id);
        $query = Project::find()->where(['planner' => $user['name']])->with(['flowType' => function($res) {
            $res->andWhere(['hj_flow_type.valid' => 1]);
        }]);
        $query->andWhere(['{{%project}}.valid'=>1]);
        $pageSize = 10;
        if(isset($params['pageSize'])){
            $pageSize = (int)$params['pageSize'];
        }
        return new ActiveDataProvider([
            // 使用with方法实现贪加载
            'query' => $query,
            // 分页信息
            'pagination' => [
                'pageSize' => $pageSize,
            ],
            // 排序信息
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC,
                ]
            ],
        ]);
    }

    public function actionView() {
        $params = \Yii::$app->request->getQueryParams();
        $query = Project::find()->where(['id' => (int)$params['id']])->with(['department', 'projectFh','projectYt', 'flowType' => function($res) {
            $res->andWhere(['valid' => 1]);
        }])->one();
        return $query;
    }

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function actionCreate(){
        $data = \Yii::$app->request->getBodyParams();
        $model = new Project();
        $model->load($data, '');
        $model->input_user_id = \Yii::$app->user->id;
        $model->created_at = $model->updated_at = time();
        if($model->save()){
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $model
            ];
        }
        return [
            'bCode' => Status::FAIL,
            'bData' => $model->errors
        ];
    }

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpdate(){
        $data = \Yii::$app->request->getBodyParams();
        $model = Project::findOne((int)$data['id']);
        $model->load($data, '');
        $model->input_user_id = \Yii::$app->user->id;
        $model->updated_at = time();
        if($model->save()){
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $model
            ];
        }
        return [
            'bCode' => Status::FAIL,
            'bData' => $model->errors,
            'model' => $model
        ];
    }

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpdateFh(){
        $data = \Yii::$app->request->getBodyParams();
        $model = Project::findOne((int)$data['id']);

        if (isset($data['projectFh']) && $data['projectFh']['id'] > 0) {
            $projectFh = ProjectFh::findOne((int)$data['projectFh']['id']);
        } else {
            $projectFh = new ProjectFh();
        }

        $model->load($data, '');
        $projectFh->load($data['projectFh'], '');
        $projectFh->inputer= \Yii::$app->user->id;
        $projectFh->update_at = time();
        if($model->save() && $projectFh->save()){
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $model,
                'projectFh' => $projectFh,
            ];
        }
        return [
            'bCode' => Status::FAIL,
            'bData' => $model->errors,
            'projectFh' => $projectFh->errors,
        ];
    }

    /**
     * @throws \yii\base\InvalidConfigException
     */
    public function actionUpdateYt(){
        $data = \Yii::$app->request->getBodyParams();
        $model = Project::findOne((int)$data['id']);

        if (isset($data['projectYt']) && $data['projectYt']['id'] > 0) {
            $projectYt = projectYt::findOne((int)$data['projectYt']['id']);
        } else {
            $projectYt = new projectYt();
        }
        $projectYt->load($data['projectYt'], '');
        $model->load($data, '');
        if($model->save() && $projectYt->save()){
            return [
                'bCode' => Status::SUCCESS,
                'bData' => $model,
                'projectYt' => $projectYt
            ];
        }
        return [
            'bCode' => Status::FAIL,
            'bData' => $model->errors,
            'projectYt' => $projectYt->errors
        ];
    }

    // 统计完成状态的不同的项目数量
    private function getCount($params, $status) {
        $query = Project::find()->where(['progress_status' => $status])->asArray()->with('customer');

        if (isset($params['start_at'])) {
            $query->andWhere(['>=', 'created_at', round($params['start_at'] / 1000)]);
        }

        if (isset($params['end_at'])) {
            $query->andWhere(['<=', 'created_at', round($params['end_at'] / 1000)]);
        }
//        return $params;
        if(isset($params['customer_id']))
        {
            $query->andWhere(['customer_id' => $params['customer_id']]);
        }
        $count = $query->count();
        return $count;
    }

    // 根据项目类型统计项目数量
    private function getCountSum($params, $status) {
        $query = Project::find()->where(['project_type_id' => $status])->asArray();

        if(isset($params['start_at'])) {
            $query->andWhere(['>=', 'created_at', round($params['start_at'] / 1000)]);
        }

        if(isset($params['end_at'])) {
            $query->andWhere(['<=', 'created_at', round($params['end_at'] / 1000)]);
        }

        if(isset($params['customer_id']))
        {
            $query->andWhere(['customer_id' => $params['customer_id']]);
        }
        $countSum = $query->count();
        return $countSum;
    }

    public function actionTestGetCountSum(){
        $params = [
            'start_at' => 1514736000000,
            'end_at' => 1539187200000,
        ];
        $status = 1;
        return $this->getCountSum($params, $status);
    }

    public function actionGetTime(){
        $params = \Yii::$app->request->getQueryParams();
        return strtotime($params['date']);
    }

    public function actionTotal() {
        $params = \Yii::$app->request->getQueryParams();

        $complete = $this->getCount($params, 0);
        $unComplete = $this->getCount($params, 1);
        $overTime = $this->getCount($params, 2);
        $firstId = $this->getCountSum($params, 1);
        $secondId = $this->getCountSum($params, 2);
        $thirdId = $this->getCountSum($params, 3);
        $fourthId = $this->getCountSum($params, 4);
        $statusArr = [
            'complete' => $complete,
            'unComplete' => $unComplete,
            'overTime' => $overTime
        ];
        $flowArr = [
            'firstId' => $firstId,
            'secondId' => $secondId,
            'thirdId' => $thirdId,
            'fourthId' => $fourthId
        ];
        $count = [
           'statusArr' => $statusArr,
           'flowArr' => $flowArr
        ];

        return $count;
    }

    public function actionContract() {
        //获取合同金额(年)
        $start_time = strtotime(date('Y-01-01'));
        $end_time = strtotime( date('Y-12-31'));
        $params = [
          'start' =>  $start_time,
          'end' =>  $end_time
        ];
        $params['contract_type'] = 1;
        $params['branch_id'] = 2;
        $params['valid'] = 1;
        $contractYearOne = Project::contractSum($params, 'money_total'); // 合同额年自主

        $projectNumOne = Project::projectSum($params); // 累计项目年
        $params['progress_status'] = 1;
        $projectComOne = Project::projectSum($params); // 累计完成项目年
        unset($params['progress_status']);
        $params['valid'] = 0;
        $projectValidOne = Project::projectSum($params); // 无效项目

        $params['contract_type'] = 2;
        $params['branch_id'] = 2;
        $params['valid'] = 1;
        $contractYearTwo = Project::contractSum($params, 'money_total'); // 合同额年挂靠
        $projectNumTwo = Project::projectSum($params); // 累计项目年
        $params['progress_status'] = 1;
        $projectComTwo = Project::projectSum($params); // 累计完成项目年
        unset($params['progress_status']);
        $params['valid'] = 0;
        $projectValidTwo = Project::projectSum($params); // 无效项目

//        return $params;
        $params['contract_type'] = 3;
        $params['branch_id'] = 2;
        $params['valid'] = 1;
        $contractYearThree = Project::contractSum($params, 'money_total'); // 合同额年分包
        $projectNumThree = Project::projectSum($params); // 累计项目年
        $params['progress_status'] = 1;
        $projectComThree = Project::projectSum($params); // 累计完成项目年
        $params['valid'] = 0;
        unset($params['progress_status']);
        $projectValidThree = Project::projectSum($params); // 无效项目
        // 按月统计的数据
        unset($params);

        $month_start = strtotime(date('Y-m-01', time()));
        $month_end = strtotime(date('Y-m-t', time()));
        $params = [
            'start' =>  $month_start,
            'end' =>  $month_end
        ];
        $params['branch_id'] = 2;
        $params['valid'] = 1;

        $params['contract_type'] = 1;
        $projectMonthOne = Project::projectSum($params); // 累计新建项目(月)自主

        $params['contract_type'] = 2;
        $projectMonthTwo = Project::projectSum($params); // 累计新建项目挂靠(月)

        $params['contract_type'] = 3;
        $projectMonthThree = Project::projectSum($params); // 累计新建项目分包(月)
        // 获取累计收款
        unset($params);
        $params['branch_id'] = 2;
        $params['valid'] = 1;
        //累计可收款项年
        $start_time = strtotime(date('Y-01-01'));
        $end_time = strtotime( date('Y-12-31'));
        $params = [
            'start' =>  $start_time,
            'end' =>  $end_time
        ];
        $resOne = Project::costHistory($params);
        // 获取累计可收款项月
        unset($params);
        $params['branch_id'] = 2;
        $params['valid'] = 1;
        $month_start = strtotime(date('Y-m-01', time()));
        $month_end = strtotime(date('Y-m-t', time()));
        $params = [
            'start' =>  $month_start,
            'end' =>  $month_end
        ];
        $resTwo = Project::costHistory($params);
        $params['contract_type'] = 1;
        $contractMonthOne = Project::contractSum($params, 'money_total'); // 合同额月自主
        $params['contract_type'] = 2;
        $contractMonthTwo = Project::contractSum($params, 'money_total'); // 合同额月挂靠
        $params['contract_type'] = 3;
        $contractMonthThree = Project::contractSum($params, 'money_total'); // 合同额月分包

        $result = [
            '1' => [
                'type' => '自主',
                'contractYear' => $contractYearOne,
                'projectNum' => $projectNumOne,
                'projectCom' => $projectComOne,
                'projectValid' => $projectValidOne,
                'projectMonth' => $projectMonthOne,
                'hisOne' => $resOne['hisOne'],
                'hisTwo' => $resTwo['hisOne'],
                'contractMonth' => $contractMonthOne,
            ],
            '2' => [
                'type' => '挂靠',
                'contractYear' => $contractYearTwo,
                'projectNum' => $projectNumTwo,
                'projectCom' => $projectComTwo,
                'projectValid' =>$projectValidTwo,
                'projectMonth' => $projectMonthTwo,
                'hisOne' => $resOne['hisTwo'],
                'hisTwo' => $resTwo['hisTwo'],
                'contractMonth' => $contractMonthTwo,
            ],
            '3' => [
                'type' => '分包',
                'contractYear' => $contractYearThree,
                'projectNum' => $projectNumThree,
                'projectCom' => $projectComThree,
                'projectValid' =>$projectValidThree,
                'projectMonth' => $projectMonthThree,
                'hisOne' => $resOne['hisThree'],
                'hisTwo' => $resTwo['hisThree'],
                'contractMonth' => $contractMonthThree,
            ]
        ];
        return $result;
    }

}




